<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { DocumentAdd, Search, Sort } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
import { knowledgeEditServe, knowledgeUploadServe } from '@/api/knowledge'

const {
  user: { name }
} = useUserStore()

const emit = defineEmits(['onShowFile', 'refresh'])

//参数
const drawerVisible = ref(false)
const formOriginModel = { contributor: name, filetitle: '', filedescription: '', file: null }
const formModel = ref({})
const fileList = ref([])
const formRef = ref()
const rules = {
  contributor: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { pattern: /^\S{1,15}$/, message: '不超过15非空字符' }
  ],
  filetitle: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { pattern: /^(?=.*[^\s]).{1,30}$/, message: '不超过30字符' }
  ],
  filedescription: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { pattern: /^(?=.*[^\s]).{1,100}$/, message: '不超过100字符' }
  ]
}

//打开
const title = ref('')
const upFileFlag = ref(0)
const onOpenUpload = (row) => {
  upFileFlag.value = 0
  drawerVisible.value = true
  if (row) {
    upFileFlag.value = 1
    title.value = '修改文件'
    formModel.value = { ...row }
  } else {
    title.value = '上传文件'
    formModel.value = { ...formOriginModel }
  }
  fileList.value = []
  formRef.value.resetFields()
}

//检查
const beforeUpload = (rawFile) => {
  const isLt300M = rawFile.size / 1024 / 1024 < 300
  if (!isLt300M) {
    ElMessage.warning({ message: '上传文件大小不能超过 300MB!', offset: 70 })
    return false
  }
  if (rawFile.type !== 'application/pdf') {
    ElMessage.error({ message: '请上传pdf格式文件!', offset: 70 })
    return false
  }
  return true
}
//变化
const handleChange = (file, fileList) => {
  if (beforeUpload(fileList[0].raw)) {
    if (fileList.length > 0) {
      if (upFileFlag.value == 1) {
        upFileFlag.value = 2
      }
      formModel.value.file = fileList[0].raw
    }
  } else {
    uploadRef.value.clearFiles()
  }
}
//超限
const uploadRef = ref()
const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value.handleStart(file)
}
//移除
const beforeRemove = () => {
  formModel.value.file = null
}
//查看
const showFile = (file) => {
  const pdfUrl = URL.createObjectURL(file.raw)
  const newWindow = window.open(pdfUrl, '_blank')
  if (!newWindow) {
    ElMessage.success({ message: '无法打开新窗口，请检查浏览器设置', offset: 70 })
  }
}

//查看已上传
const onShowFile = () => {
  emit('onShowFile', formModel.value.id)
}

//提交
const onEnter = async () => {
  await formRef.value.validate()
  if (!formModel.value.file && upFileFlag.value == 0) {
    ElMessage.warning({ message: '请选择PDF文件', offset: 70 })
    return
  }
  if (formModel.value.file == null) {
    delete formModel.value['file']
  }
  //name
  formModel.value.contributor = name
  if (upFileFlag.value == 0) await knowledgeUploadServe(formModel.value)
  else await knowledgeEditServe(formModel.value)
  ElMessage.success({ message: '提交成功', offset: 70 })
  drawerVisible.value = false
  emit('refresh', upFileFlag.value)
}

defineExpose({
  onOpenUpload
})
</script>

<template>
  <el-drawer v-model="drawerVisible" :title="title" direction="rtl" size="40%">
    <el-form :model="formModel" :rules="rules" ref="formRef">
      <el-form-item label="作者" prop="contributor">
        <el-input
          v-model="formModel.contributor"
          placeholder="请输入作者"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="标题" prop="filetitle">
        <el-input v-model="formModel.filetitle" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="filedescription">
        <el-input
          v-model="formModel.filedescription"
          style="width: 500px"
          :rows="4"
          type="textarea"
          placeholder="请输入文件描述"
        />
      </el-form-item>
      <el-form-item label="选择文件">
        <div>
          <div>
            <el-button type="primary" v-if="upFileFlag !== 0" @click="onShowFile" :icon="Search">
              原上传文件
            </el-button>
          </div>
          <div>
            <el-upload
              style="width: 300px; margin-top: 10px"
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-change="handleChange"
              :before-remove="beforeRemove"
              :on-preview="showFile"
              :auto-upload="false"
              :file-list="fileList"
              :limit="1"
              :accept="'application/pdf'"
            >
              <template v-slot:trigger>
                <el-button type="primary" v-if="upFileFlag == 0" :icon="DocumentAdd">
                  选择文件
                </el-button>
                <el-button type="primary" v-else :icon="Sort">选择替换</el-button>
              </template>
              <template v-slot:tip>
                <div class="el-upload__tip" v-if="upFileFlag == 0">小于 300MB 的pdf文件</div>
                <div class="el-upload__tip" v-else-if="upFileFlag == 1">
                  选择替换则覆盖原上传的文件
                </div>
                <div class="el-upload__tip" v-else-if="upFileFlag == 2">清空下方则取消替换</div>
              </template>
            </el-upload>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onEnter"> 提交上传 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped></style>
